package in.edupack.hibernate.hql;

import in.edupack.hibernate.pojo.Student;

import java.util.Iterator;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * This class show how to use HQL
 * @author Bibek
 * Remember HQL uses class and field name instead of database table and column names
 */
public class HQLExample {
	public static void main(String[] args) {
		HQLExample hqlExample = new HQLExample();
		//hqlExample.simpleSelect();
		hqlExample.columnSelect();
	}

	private void columnSelect() {
	 Session session  = null;
	 SessionFactory factory = new Configuration().configure("in/edupack/hibernate/config/hbm-config.xml").buildSessionFactory();
	 session = factory.openSession();
	 
	 String hqlQuery = "select student.id,student.name from Student student";	
	 // or the above query can have where clause as below
	 String hqlWhereQuery = "select student.id,student.name from Student student where student.id=1";
	 // in similar fashion order by ,group by, sql function
	 
	 Query query = session.createQuery(hqlWhereQuery);
	 
	 //Here you cannt store the result in Student object instead you will get the result as an Object Array
	 Iterator it = query.iterate();
	 
	 while (it.hasNext())
	 {
		 Object[] row = (Object[])it.next();
		 System.out.println("ID "+row[0] + " Name "+row[1]);
		 // Below code throws error
		 //Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to in.edupack.hibernate.pojo.Student
		 /*
		 Student student = (Student)it.next();
		 System.out.println("ID "+student.getId() + " Name "+student.getName());
		 */
	 }
	 
		session.close();
		
	}

	private void simpleSelect() {
	 Session session  = null;
	 SessionFactory factory = new Configuration().configure("in/edupack/hibernate/config/hbm-config.xml").buildSessionFactory();
	 session = factory.openSession();
	 
	 String hqlQuery = "from Student student";	 
	 Query query = session.createQuery(hqlQuery);	 
	 Iterator<Student> it = query.iterate();
	 
	 while (it.hasNext())
	 {
		 Student student = it.next();
		 System.out.println("ID "+student.getId() + " Name "+student.getName());
	 }
	 
		session.close();
	}

}
